package com.taotao.portal.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.HttpClientUtil;
import com.taotao.common.utils.JsonUtils;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.pojo.TbItemParamItem;
import com.taotao.portal.pojo.PortalItem;

@Service
public class ItemServiceImpl implements ItemService {
	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	@Value("${REST_ITEM_BASE_URL}")
	private String REST_ITEM_BASE_URL;
	@Value("${REST_ITEM_DESC_URL}")
	private String REST_ITEM_DESC_URL;
	@Value("${REST_ITEM_PARAM_URL}")
	private String REST_ITEM_PARAM_URL;

	/**
	 * 调用taotao-rest商品信息的服务
	 */
	@Override
	public TbItem getItemById(long itemId) {
		String json = HttpClientUtil.doGet(REST_BASE_URL + REST_ITEM_BASE_URL
				+ itemId);
		TaotaoResult result = TaotaoResult.formatToPojo(json, PortalItem.class);
		TbItem item = (TbItem) result.getData();
		return item;
	}

	/**
	 * 调用taotao-rest商品描述信息的服务
	 */
	@Override
	public String getItemDescById(long itemId) {
		String json = HttpClientUtil.doGet(REST_BASE_URL + REST_ITEM_DESC_URL
				+ itemId);
		TaotaoResult result = TaotaoResult.formatToPojo(json, TbItemDesc.class);
		TbItemDesc itemDesc = (TbItemDesc) result.getData();
		String desc = itemDesc.getItemDesc();
		return desc;
	}

	/**
	 * 调用taotao-rest商品规格参数信息的服务
	 */
	@Override
	public String getItemParamByItemId(long itemId) {
		String json = HttpClientUtil.doGet(REST_BASE_URL + REST_ITEM_PARAM_URL
				+ itemId);
		TaotaoResult result = TaotaoResult.formatToPojo(json,
				TbItemParamItem.class);
		TbItemParamItem itemParamItem = (TbItemParamItem) result.getData();
		// 去规格参数
		String itemParam = itemParamItem.getParamData();
		// json字符串转化为list
		List<Map> mapList = JsonUtils.jsonToList(itemParam, Map.class);
		// 根据list生成html
		StringBuffer sb = new StringBuffer();
		sb.append("<table cellpadding=\"0\" cellspacing=\"1\" width=\"100%\" border=\"0\" class=\"Ptable\">\n");
		sb.append("     <tbody>\n");
		//遍历
		for (Map param : mapList) {
			sb.append("          <tr>\n");
			sb.append("               <th class=\"tdTitle\" colspan=\"2\">"
					+ param.get("group") + "</th>\n");
			sb.append("          </tr>\n");
			// 取规格项
			List<Map> object = (List<Map>) param.get("params");
			for (Map map : object) {
				sb.append("          <tr>\n");
				sb.append("               <td class=\"tdTitle\">"
						+ map.get("k") + "</td>\n");
				sb.append("               <td>" + map.get("v") + "</td>\n");
				sb.append("          </tr>\n");
			}
		}
		sb.append("     </tbody>\n");
		sb.append("</table>");
		return sb.toString();
	}

}
